package com.bw.xiaosy.shiro;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证过滤器
 *
 * @author Xiaosy
 * @date 2017-03-20 17:37
 */
public class MyAuthorizationFilter extends PermissionsAuthorizationFilter {
    @Override
    public boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String path = request.getServletPath();
        NotAuthorizationBean bean = new NotAuthorizationBean(path);
        if(ShiroUtil.isContains(bean))
        {
            //不需要认证
            return true;
        }
        return super.isAccessAllowed(servletRequest,servletResponse,o);
    }
    /**
     * 健全失败，统一返回403，由前端页面弹窗提示
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
            throws IOException {
        Subject subject = getSubject(request,response);
        if(subject.getPrincipal() == null)
        {
            ShiroUtil.writeResponse((HttpServletResponse) response,new Result(AuthorizationStatus.NOT_LOGIN));
        }else{
            ShiroUtil.writeResponse((HttpServletResponse) response,new Result(AuthorizationStatus.NOT_AUTHORIZATION));
        }

        return false;
    }

}
